'use strict'

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const devMode = process.env.NODE_ENV === 'production'
module.exports = {
  // mode: 'development',
  mode: 'production',
  // 入口文件
  entry: {
    main: './src/ts/index.ts',
  },
  context: path.resolve(__dirname),
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'scripts/[name].[contenthash].js',
    publicPath: devMode ? './' : '',
    environment: {
      arrowFunction: false,
    },
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: [
                [
                  '@babel/preset-env',
                  // {  "targets": "> 0.25%, not dead" }  // 全球使用人数大于0.25%且还没有废弃的版本
                  // https://github.com/browserslist/browserslist
                  {
                    targets: '> 0.25%, not dead',
                    corejs: '3',
                    useBuiltIns: 'usage',
                  },
                ],
              ],
            },
          },
          'ts-loader',
        ],
        exclude: /node-modules/,
      },
      {
        test: /\.(css|less)$/,
        use: [
          devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                pulgins: [
                  [
                    'postcss-preset-eenv',
                    {
                      browsers: ['> 1%', 'last 2 versions', 'not ie <= 8'],
                    },
                  ],
                ],
              },
            },
          },
          'less-loader',
        ],
      },
    ],
  },
  //设置可引用模块文件类型
  resolve: { extensions: ['.ts', '.js'] },
  // devtool: 'source-map',
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, './src/index.html'),
      chunks: ['main'],
      filename: 'index.html',
    }),
    new MiniCssExtractPlugin({
      filename: devMode ? 'css/[name].css' : 'css/[name].[hash].css',
      chunkFilename: devMode ? 'css/[id].css' : 'css/[id].[hash].css',
    }),
  ],
}
